/**
 * 表单填报 编辑页
 *
 * 作者 zhangwei
 * 日期 2024-09-05 08:53:07
 */
var demojs = [],formVal={}
//JavaScript代码区域
layui.use(['formDesigner', 'form','layer','upload','element','febs'], function () {
    var layer = layui.layer;
    var $ = layui.jquery;
    var upload  = layui.upload;
    var element = layui.element
    var index = layui.index,
        febs = layui.febs
    var formDesigner = layui.formDesigner;
    var form = layui.form;
    var render
    var $view = $('#formInput')
    // 1是新增，2是编辑
    var type = POPUP_DATA.type

    if (formFillData !== undefined) {
        demojs = JSON.parse(formFillData.formHtml)
        if(type == 2){
            // 编辑取formJson
            formVal =  JSON.parse(formFillData.formJson)
        }
        render = formDesigner.render({
            elem: '#formInput',
            data: demojs,
            viewOrDesign:true,
            previewElem:'#formInput',
            formData: formVal
        });
        var curBtnId
        var images = render.getImages();

        // 编辑回显图片和文件
        initImg()
        function initImg(){
            if(images && images.length>0){
                images.forEach(item => {
                    let imgHtml = ''
                    if(formVal[item.id] && formVal[item.id].length>0){
                        formVal[item.id].forEach( imgItem => {
                            imgHtml+='<div id="" class="file-iteme" style="position: relative;border: 1px solid #eee;">' +
                                '<i class="layui-icon layui-icon-delete" onclick="removeImg(event)" data-id="'+ imgItem.id +'" style="font-size: 21px;color:red;position: absolute;right: -2px;top: -6px;z-index: 999;cursor: pointer;"></i>' +
                                '<img style="width: 100px;height: 100px;" data-filepath="'+ imgItem.filePath +'" data-filename="'+ imgItem.fileName +'" data-smallpath="'+ imgItem.smallPath +'" src=' + ctx + imgItem.filePath + '>' +
                                '<div class="info">' + imgItem.fileName + '</div>' +
                                '</div>'
                        })
                        $('#uploader-list-'+item.id).append(imgHtml)
                        $('#uploader-list-'+item.id).parents('.layui-input-block').show()
                    }

                })
            }
        }
        // 上传图片初始化
        var uploadInst = upload.render({
            elem: '#commonUploadImgBtn',
            url: ctx +'formDesign/upload',
            accept: "images",
            method: 'post',
            multiple: true,
            size: 5120,
            before: function (obj) {
                layer.msg('图片上传中...', {
                    icon: 16,
                    shade: 0.01,
                    time: 0
                })
            },
            done: function (res) {
                layer.close(layer.msg());//关闭上传提示窗口
                if(res.code == 200) {
                    $view.find('#uploader-list-' + curBtnId).append(
                        '<div id="" class="file-iteme" style="position: relative;border: 1px solid #eee;">' +
                        '<i class="layui-icon layui-icon-delete" onclick="removeImg(event)" data-id="'+ curBtnId +'" style="font-size: 21px;color:red;position: absolute;right: -2px;top: -6px;z-index: 999;cursor: pointer;"></i>' +
                        '<img style="width: 100px;height: 100px;" data-filepath="'+ res.data.filePath +'" data-filename="'+ res.data.fileName +'" data-smallpath="'+ res.data.smallPath +'" src=' + ctx + res.data.filePath + '>' +
                        '<div class="info">' + res.data.fileName + '</div>' +
                        '</div>'
                    );
                    $view.find('#uploader-list-' + curBtnId).parents('.layui-input-block').show()
                }
            },
            error: function (index) {

            },allDone: function () {

            }
        })
        // 上传图片按钮点击
        $view.find('.uploadImgBtn').on('click',function (){
            curBtnId = $(this).attr('data-id')
            uploadInst.reload();
            $('#commonUploadImgBtn').click()
        })
        window.removeImg =  function (event){
            let id = $(event.target).data('id')
            let length = $(event.target).parent().parent().find('.file-iteme').length
            if(length == 1){
                $(event.target).parents('.layui-input-block').hide()
            }
            $(event.target).parent().remove()
        }
        // 初始化上传文件
        var filesData = render.getFiles();
        var fileSize =''
        for (var i = 0; i < filesData.length; i++) {
            let elem = $view.find('#' + filesData[i].select)
            let elemList = $view.find('#list-' + filesData[i].id)
            upload.render({
                elem: elem
                , elemList: elemList //列表元素对象
                , url: '' + filesData[i].uploadUrl + ''
                , accept: 'file'
                , multiple: true
                , number: 3
                , auto: true
                , choose: function (obj) {

                    var that = this;
                    var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                    //读取本地文件
                    obj.preview(function (index, file, result) {
                        fileSize = (file.size / 1014).toFixed(1) + 'kb'
                        var tr = $(['<tr id="upload-' + index + '">'
                            , '<td>' + file.name + '</td>'
                            , '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
                            , '<td><div class="layui-progress" lay-filter="progress-demo-' + index + '"><div class="layui-progress-bar" lay-percent=""></div></div></td>'
                            , '<td>'
                            , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                            , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                            , '</td>'
                            , '</tr>'].join(''));

                        //单个重传
                        tr.find('.demo-reload').on('click', function () {
                            obj.upload(index, file);
                        });

                        //删除
                        tr.find('.demo-delete').on('click', function () {
                            delete files[index]; //删除对应的文件
                            let length = tr.parents('tbody').find('tr').length
                            if(length == 1){
                                tr.parents('.layui-input-block').hide()
                            }
                            tr.remove();

                            // uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                        });
                        // $($view.find('#list-' + filesData[i].id)).append(tr)
                        that.elemList.append(tr);
                        that.elemList.parents('.layui-input-block').show()
                        element.render('progress','progress-demo-' + index); //渲染新加的进度条组件
                    });
                }
                , done: function (res, index, upload) { //成功的回调
                    var that = this;
                    //if(res.code == 0){ //上传成功
                    var tr = that.elemList.find('tr#upload-' + index)
                        , tds = tr.children();
                    tr.attr('data-filepath',res.data.filePath)
                    tr.attr('data-filename',res.data.fileName)
                    $(tr).attr('data-smallpath',res.data.smallPath)
                    $(tr).attr('data-filesize',fileSize)
                    // tds.eq(3).html(''); //清空操作
                    delete this.files[index]; //删除文件队列已经上传成功的文件
                    return;
                    //}
                    this.error(index, upload);
                }
                , allDone: function (obj) { //多文件上传完毕后的状态回调
                    console.log(obj)
                }
                , error: function (index, upload) { //错误回调
                    var that = this;
                    var tr = that.elemList.find('tr#upload-' + index)
                        , tds = tr.children();
                    tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
                }
                , progress: function (n, elem, e, index) {
                    element.progress('progress-demo-' + index, n + '%'); //执行进度条。n 即为返回的进度百分比
                }
            });
        }
        initFiles()
        function initFiles(){
            if(filesData && filesData.length>0){
                filesData.forEach(item => {
                    let fileHtml = ''
                    if(formVal[item.id] && formVal[item.id].length>0){
                        $('#list-'+item.id).empty()
                        formVal[item.id].forEach( fileItem => {
                            fileHtml+='<tr id="upload-' + item.id + '" data-filesize="'+ fileItem.fileSize +'" data-filepath="'+ fileItem.filePath +'" data-filename="'+ fileItem.fileName +'" data-smallpath="'+ fileItem.smallPath +'">'+
                                '<td>' + fileItem.fileName + '</td>'+
                                '<td>' + fileItem.fileSize + '</td>'+
                                '<td><div class="layui-progress" lay-filter="progress-demo-' + item.id + '"><div class="layui-progress-bar" lay-percent="100%"></div></div></td>'+
                                '<td>'+
                                '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'+
                                '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'+
                                '</td>'+
                                '</tr>'
                            $('#list-'+item.id).append(fileHtml)
                            $('#list-'+item.id).parents('.layui-input-block').show()
                            element.progress('progress-demo-' + item.id, '100%'); //执行进度条。n 即为返回的进度百分比
                        })
                    }

                })

            }
        }
    }

        $view.find('.demo-delete').click(function(){
            let length = $(this).parents('tbody').find('tr').length
            if(length == 1){
                $(this).parents('.layui-input-block').hide()
            }
            $(this).parents('tr').remove()
        })
    //监听提交
    form.on('submit(formDemoSubmit)', function(data){
        var json = render.getFormData();
        let dataT = render.getOptions()
        let img =  render.getImages()
        let file = render.getFiles()
        let edit =  render.geticeEditorObjects()
        let datas =  render.getData()
        // 文件必填校验
        let fileFlg = false,imgFlg = false
        // 获取页面上传图片
        $view.find('.uploader-list').each((v,h) => {
            let required = $(h).attr('data-require')
            let imgLabelId = $(h).attr('data-id')
            let length = $(h).find('img').length
            if(required =='true' && length==0){
                imgFlg = true
                return false
            }
            let arrImg = []
            $(h).find('img').each((v,h) => {
                let filePath = $(h).attr('data-filepath')
                let fileName = $(h).attr('data-filename')
                let smallPath = $(h).attr('data-smallpath')
                arrImg.push({
                    filePath:filePath,
                    fileName:fileName,
                    smallPath:smallPath
                })
            })
            json[imgLabelId] = arrImg
        })
        // 获取页面文件上传
        $view.find('.uploader-list-file').each((v,h) => {
            let required = $(h).attr('data-require')
            let fileLabelId = $(h).attr('data-id')
            let length = $(h).find('tbody tr').length
            if (required=='true' && length == 0) {
                fileFlg = true
                return false
            }
            let arrFile = []
            $(h).find('tbody tr').each((v,h) => {
                let filePath = $(h).attr('data-filepath')
                let fileName = $(h).attr('data-filename')
                let smallPath = $(h).attr('data-smallpath')
                let fileSize = $(h).attr('data-filesize')
                arrFile.push({
                    filePath:filePath,
                    fileName:fileName,
                    smallPath:smallPath,
                    fileSize:fileSize
                })
            })
            json[fileLabelId] = arrFile
        })
        if(fileFlg){
            febs.alert.warn('文件没有上传');
            return false
        }
        if(imgFlg){
            febs.alert.warn('图片没有上传');
            return false
        }
        // layer.msg( JSON.stringify(json), {icon: 6});
        let submitData= formFillData
        submitData.formJson = JSON.stringify(json)
        addOrUpdate(submitData)
        return false;
    });
    function addOrUpdate(data) {
        let tips='是否保存'
        let submitFlg= window.localStorage.getItem('submitFlg','2')
        if(submitFlg==1){
            tips='是否保存'
        }else{
            tips='是否提交'
        }
        data.submitFlg = submitFlg
        febs.modal.confirm("提示！",tips,function (index){
            if (data.registerId && data.registerId.length > 0) {
                febs.postArray(ctx + 'formFill/update', data, function () {
                    layer.closeAll();
                    febs.alert.success('保存成功');
                    $('#febs-formFill').find('#query').trigger('click');
                });
            } else {
                febs.postArray(ctx + 'formFill', data, function () {
                    layer.closeAll();
                    febs.alert.success('保存成功');
                    $('#febs-formFill').find('#query').trigger('click');
                });
            }
        })
    }

});